package org.zjx.app.action.route;

import com.alibaba.fastjson2.JSON;
import org.zjx.analysis.analyze.game.GameAnalysis;
import org.zjx.command.entity.ItemInstance;
import org.zjx.command.entity.Route;
import org.zjx.command.entity.RouteQueryPojo;
import org.zjx.command.entity.screen.Address;
import org.zjx.command.enums.SlotType;
import org.zjx.command.state.AccountState;
import org.zjx.command.state.ItemState;
import org.zjx.data.route.RouteManager;
import org.zjx.data.route.impl.*;
import org.zjx.window.action.Action;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class BaseRouteAction extends Action {
    private final Address targetAddress;

    public BaseRouteAction(IWindow targetWindow, Address targetAddress) {
        super(targetWindow, false);
        this.targetAddress = targetAddress;
    }

    @Override
    protected void doExecute() throws Exception {
        AccountState accountState = stateManager.getState(AccountState.class);
        RouteQueryPojo routeQueryPojo = new RouteQueryPojo(getAddressNow(), targetAddress, accountState.getSect());
        routeQueryPojo.setInTeam(stateManager.getGameState().isInTeam());
        analyzeProps(routeQueryPojo);

        List<Route> routes = RouteManager.getInstance().findPath(routeQueryPojo);
        for (Route route : routes) {
            if (route instanceof BackToSectRoute) {
                Address toAddress = accountState.getSect().getF8Location();
                targetWindow.submitAction(new BackToSectAction(targetWindow, toAddress));
            } else if (route instanceof FlyingCharmRoute) {
                targetWindow.submitAction(new FlyingCharmAction(targetWindow, route.getEnd().getCity()));
            } else if (route instanceof FlyingFlagRoute) {
                targetWindow.submitAction(new FlyingFlagAction(targetWindow, route.getEnd()));
            } else if (route instanceof RoomEnterRoute) {
                Address clickAddress = new Address(route.getStart().getCity(), ((RoomEnterRoute) route).getClickX(), ((RoomEnterRoute) route).getClickY());
                targetWindow.submitAction(new RoomInterAction(targetWindow, route.getEnd(),route.getStart(),clickAddress));
            }else if (route instanceof RunningRoute) {
                targetWindow.submitAction(new RunningAction(targetWindow,route.getEnd()));
            }else if (route instanceof SceneTransferRoute) {
                Address clickAddress = new Address(route.getStart().getCity(), ((SceneTransferRoute) route).getClickX(), ((SceneTransferRoute) route).getClickY());
                targetWindow.submitAction(new SceneTransferAction(targetWindow, route.getEnd(),route.getStart(),clickAddress));
            }else if (route instanceof NpcTransferRoute) {
                Address clickAddress = new Address(route.getStart().getCity(), ((NpcTransferRoute) route).getClickX(), ((NpcTransferRoute) route).getClickY());
                targetWindow.submitAction(new NpcTransferAction(targetWindow, route.getEnd(),route.getStart(),clickAddress,((NpcTransferRoute) route).getDialogues()));

            }
        }
    }

    public Address getAddressNow() {
        GameAnalysis gameAnalysis = new GameAnalysis(targetWindow);
        return gameAnalysis.getAddress();
    }

    private void analyzeProps(RouteQueryPojo routeQueryPojo) {
        ItemState state = stateManager.getState(ItemState.class);
        if (state == null) return;
        List<ItemInstance> instances = state.getItemsByType(SlotType.INVENTORY);

        //飞行符 信息
        boolean hasFlyingCharm = !state.findItemsByTemplate("飞行符").isEmpty();
        routeQueryPojo.setHasFlyingCharm(hasFlyingCharm);

        //合成旗信息
        List<ItemInstance> flag = instances.stream().filter(itemInstance -> itemInstance != null && itemInstance.getName().contains("合成旗")).collect(Collectors.toList());
        for (ItemInstance instance : flag) {
            if (!instance.getAttributes().containsKey("场景") || !instance.getAttributes().containsKey("points"))
                continue;
            String city = (String) instance.getAttributes().getOrDefault("场景", "");
            List<Point> points = parsePoints(instance.getAttributes().get("points"));
            if (city.isEmpty() || points == null || points.isEmpty()) continue;
            routeQueryPojo.getFlyingFlagsPoints().put(city, points);
        }
        System.out.println("寻路道具加载完毕。。。");
    }

    public List<Point> parsePoints(Object pointsData) {
        if (pointsData == null) {
            return new ArrayList<>();
        }

        // 统一转换为 JSON 字符串
        String jsonStr;
        if (pointsData instanceof List) {
            jsonStr = JSON.toJSONString(pointsData); // List -> JSON
        } else {
            jsonStr = pointsData.toString();
        }

        // 尝试解析为标准 List<Point>
        try {
            return JSON.parseArray(jsonStr, Point.class);
        } catch (Exception e) {
            // 回退处理旧格式
            if (jsonStr.startsWith("java.awt.Point")) {
                return parseLegacyPointFormat(jsonStr);
            }
            return new ArrayList<>();
        }
    }

    private List<Point> parseLegacyPointFormat(String legacyStr) {
        String[] parts = legacyStr.split("\\[x=|,y=|\\]");
        if (parts.length >= 3) {
            int x = Integer.parseInt(parts[1]);
            int y = Integer.parseInt(parts[2]);
            return Collections.singletonList(new Point(x, y));
        }
        return new ArrayList<>();
    }
}
